﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using DeepEarth.Core.Data;
using System.Windows.Data;

namespace DeepEarth.Toolkit.Controls
{
    [TemplatePart(Name = PART_DragHandle, Type = typeof(ToggleButton))]
    public class ReorderableLayerPanelItem : LayerPanelItem
    {
        const string PART_DragHandle = "PART_DragHandle";
        UIElement dragHandle;

        private MouseButtonEventHandler dragInitiatedHandler;
        public MouseButtonEventHandler DragInitiatedHandler
        {
            get { return dragInitiatedHandler; }
            set
            {
                if (dragHandle != null)
                {
                    // remove existing handler
                    if (dragInitiatedHandler != null)
                        dragHandle.RemoveHandler(UIElement.MouseLeftButtonDownEvent, dragInitiatedHandler);
 
                    dragHandle.AddHandler(UIElement.MouseLeftButtonDownEvent, value, true);
                }

                dragInitiatedHandler = value;
            }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            dragHandle = (UIElement)GetTemplateChild(PART_DragHandle);

            if (dragHandle != null && DragInitiatedHandler != null)
                dragHandle.AddHandler(UIElement.MouseLeftButtonDownEvent, DragInitiatedHandler, true);
        }

        protected override DependencyObject GetContainerForItemOverride()
        {
            ReorderableLayerPanelItem lpi = new ReorderableLayerPanelItem();
            lpi.ItemTemplate = this.ItemTemplate;
            lpi.TemplateSelector = this.TemplateSelector;
            lpi.LayerPanelItemSelectedCommand = this.LayerPanelItemSelectedCommand;

            lpi.DragInitiatedHandler = this.DragInitiatedHandler;

            StackPanel p = new StackPanel();
            p.Children.Add(lpi);

            Image i = new Image();
            i.Opacity = 0.65;

            p.Children.Add(i);

            return p;
        }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            StackPanel s = element as StackPanel;
            TreeViewItem tvi = s.Children[0] as TreeViewItem;

            base.PrepareContainerForItemOverride(tvi, item);
        }
    }
}
